/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-10-16 15:25:18
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-10-16 15:59:40
 * @FilePath: /react18-vite-admin/src/views/system/MenusManage/useTable.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { useEffect } from 'react';
import type { TableProps } from 'antd';
import { useImmer } from 'use-immer';

import { useMenuTree } from '@/service/biz/menu/useMenuTree';
import { useMenuDetail } from '@/service/biz/menu/useMenuDetail';
import type { MenuTreeItem } from '@/typings/api/menu';
import Button from '@/components/ui/Button/Button';
import CenterGap10 from '@/components/ui/CenterGap10/CenterGap10';

export const useTable = () => {
    const { getTree, tree, loading } = useMenuTree();
    const { removeLoading, removeMenu } = useMenuDetail();

    const [editNsp, setEditNsp] = useImmer({
        open: false,
        parentId: undefined as number | undefined,
        id: undefined as number | undefined
    });

    const handleEdit = (parentId?: number, id?: number) => {
        setEditNsp((draft) => {
            draft.open = true;
            draft.parentId = parentId;
            draft.id = id;
        });
    };

    const handleRemove = (id: number) => {
        removeMenu(id).then(() => {
            afterUpdate();
        })
    }

    const afterUpdate = () => {
        window.location.reload();
    };

    const columns: TableProps<MenuTreeItem>['columns'] = [
        {
            title: '菜单名称',
            dataIndex: 'name'
        },
        {
            title: '菜单路径',
            dataIndex: 'path'
        },
        {
            title: '排序',
            dataIndex: 'sortWeight'
        },
        {
            title: '操作',
            render: (_, record) => (
                <CenterGap10>
                    <Button
                        type="success"
                        onClick={() => handleEdit(record.id)}
                    >
                        添加
                    </Button>
                    <Button
                        type="primary"
                        onClick={() => handleEdit(record.parentId, record.id)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="danger"
                        loading={removeLoading}
                        onClick={() => handleRemove(record.id)}
                    >
                        删除
                    </Button>
                </CenterGap10>
            )
        }
    ];

    useEffect(() => {
        getTree();
    }, []);

    return {
        loading,
        tree,
        columns,
        editNsp,
        setEditNsp,
        handleEdit,
        afterUpdate,
        removeLoading
    };
};
